import json
import logging

from docx import Document
from typing import List, Dict
import os

def load_json_data(json_path: str) -> List[Dict[str, str]]:
    """
    :param json_path:  JSON 文件路径
    :return: 日志记录列表
    """
    try:
        with open(json_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"错误：找不到文件 {json_path}")
        return []
    except json.JSONDecodeError:
        print(f"错误：JSON文件 {json_path} 格式不正确")
        return []
    except Exception as e:
        print(f"读取JSON文件时发生错误: {str(e)}")
        return []

def update_internship_diary(
        file_path: str,
        daily_records: List[Dict[str, str]],
        output_path: str = None
) -> None:
    """
    更新实习日志文档中的内容

    :param file_path:  docx 文件路径
    :param daily_records:   从 JSON 文件中加载而来的实习日志字符串
    :param output_path:    输出文件路径。可为空
    :return:

    Example:
        records = [
            {
                "internship_content": "今天完成了A项目",
                "daily_havest": "学习了团队协作"
            },
            {
                "internship_content": "参与了B项目开发",
                "daily_havest": "掌握了新技术"
            }
        ]
        update_internship_diary("实习日志.docx", records)
    """

    # 打开文档
    doc = Document(file_path)

    # 获取表格，一个表格中有两天的实习日志
    # table = doc.tables[0]

    # 每个日期占用 6 行
    rows_per_date = 6

    # 遍历日志记录，一次遍历两个元素
    for index, (prev_record, current_record) in enumerate(zip(daily_records[:-1], daily_records[1:])):
        # 获取表格，一个表格中有两天的实习日志
        if index >= len(doc.tables):
            logging.warning(f"表格生成不够，请尝试扩展表格，index={index}，表格个数：{len(doc.tables)}")
            break

        table = doc.tables[index]

        # 计算当前日期的起始行
        base_row = index * rows_per_date

        # 更新实习内容
        pre_content_row = 1
        if pre_content_row < len(table.rows):
            table.cell(pre_content_row, 1).text = prev_record["internship_content"]

        # 更新心得体会
        pre_harvest_row = 2
        if pre_harvest_row < len(table.rows):
            table.cell(pre_harvest_row, 1).text = prev_record["daily_havest"]

        # ====== 第二个 ======

        # 更新实习内容
        last_content_row = 4
        if last_content_row < len(table.rows):
            table.cell(last_content_row, 1).text = current_record["internship_content"]

        # 更新心得体会
        last_harvest_row = 5
        if last_harvest_row < len(table.rows):
            table.cell(last_harvest_row, 1).text = current_record["daily_havest"]

    # 如果没有指定输出路径，生成默认输出路径
    if output_path is None:
        file_name, file_ext = os.path.splitext(file_path)
        output_path = f"{file_name}_已更新{file_ext}"

    # 保存文档
    doc.save(output_path)
    print(f"文档已更新并保存至: {output_path}")



def generate_new_docx(doc_path, new_doc_path, records_path) :
    records = load_json_data(records_path)
    update_internship_diary(doc_path, records, new_doc_path)


if __name__ == '__main__':
    doc_path = "data/实习日志_输出.docx"
    new_doc_path = "data/实习日志-新.docx"
    records_path = "data/text_data.json"
    generate_new_docx(doc_path, new_doc_path, records_path)

